// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#include <pollux/serializers/unsafe_row_serializer.h>
#include <melon/lang/bits.h>
#include <pollux/row/unsafe_row_deserializers.h>
#include <pollux/row/unsafe_row_fast.h>
#include <pollux/serializers/row_serializer.h>

namespace kumo::pollux::serializer::spark {
    void UnsafeRowVectorSerde::estimateSerializedSize(
        const row::UnsafeRowFast *unsafeRow,
        const melon::Range<const vector_size_t *> &rows,
        vector_size_t **sizes) {
        return unsafeRow->serializedRowSizes(rows, sizes);
    }

    std::unique_ptr<IterativeVectorSerializer>
    UnsafeRowVectorSerde::createIterativeSerializer(
        RowTypePtr /* type */,
        int32_t /* numRows */,
        StreamArena *streamArena,
        const Options *options) {
        return std::make_unique<RowSerializer<row::UnsafeRowFast> >(
            streamArena->pool(), options);
    }

    void UnsafeRowVectorSerde::deserialize(
        ByteInputStream *source,
        pollux::memory::MemoryPool *pool,
        RowTypePtr type,
        RowVectorPtr *result,
        const Options *options) {
        std::vector<std::optional<std::string_view> > serializedRows;
        std::vector<std::unique_ptr<std::string> > serializedBuffers;
        RowDeserializer<std::optional<std::string_view> >::deserialize<
            RowIteratorImpl>(source, serializedRows, serializedBuffers, options);

        if (serializedRows.empty()) {
            *result = BaseVector::create<RowVector>(type, 0, pool);
            return;
        }

        *result = std::dynamic_pointer_cast<RowVector>(
            pollux::row::UnsafeRowDeserializer::deserialize(
                serializedRows, type, pool));
    }

    // static
    void UnsafeRowVectorSerde::registerVectorSerde() {
        pollux::registerVectorSerde(std::make_unique<UnsafeRowVectorSerde>());
    }

    // static
    void UnsafeRowVectorSerde::registerNamedVectorSerde() {
        pollux::registerNamedVectorSerde(
            VectorSerde::Kind::kUnsafeRow, std::make_unique<UnsafeRowVectorSerde>());
    }
} // namespace kumo::pollux::serializer::spark
